package cn.b.sky.user.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class ServletFilter extends ProxyFilter {

  private static final Logger log = LoggerFactory.getLogger(ServletFilter.class);

  private Map<UrlPatternMatcher, Servlet> servletMap = Collections.emptyMap();

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException,
      ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;

    String contextPath = req.getContextPath();
    String requestUri = req.getRequestURI();
    String path = requestUri.substring(contextPath.length());
    log.trace("path : {}", path);

    for (Map.Entry<UrlPatternMatcher, Servlet> entry : this.servletMap.entrySet()) {
      UrlPatternMatcher urlPatternMatcher = entry.getKey();

      if (urlPatternMatcher.shouldRedirect(path)) {
        String redirectUrl = contextPath + path + "/";
        log.trace("redirect to : {}", path);
        res.sendRedirect(redirectUrl);

        return;
      }

      if (urlPatternMatcher.matches(path)) {
        log.trace("{} match {}", urlPatternMatcher, path);

        PathHttpServletRequestWrapper requestWrapper = new PathHttpServletRequestWrapper(req,
            urlPatternMatcher.getUrlPattern());

        Servlet servlet = entry.getValue();
        log.trace("invoke {}", servlet);
        servlet.service(requestWrapper, response);

        return;
      }
    }

    filterChain.doFilter(request, response);
  }

  @Override
  public void init(FilterConfig filterConfig) throws ServletException {
    for (Map.Entry<UrlPatternMatcher, Servlet> entry : this.servletMap.entrySet()) {
      Servlet servlet = entry.getValue();
      servlet.init(new ProxyServletConfig(filterConfig.getServletContext()));
    }
  }

  @Override
  public void destroy() {
    for (Map.Entry<UrlPatternMatcher, Servlet> entry : this.servletMap.entrySet()) {
      Servlet servlet = entry.getValue();
      servlet.destroy();
    }
  }

  public void setServletMap(Map<String, Servlet> urlPatternMap) {

    this.servletMap = new HashMap<UrlPatternMatcher, Servlet>();

    for (Map.Entry<String, Servlet> entry : urlPatternMap.entrySet()) {
      UrlPatternMatcher urlPatternMatcher = UrlPatternMatcher.create(entry.getKey());

      this.servletMap.put(urlPatternMatcher, entry.getValue());
    }
  }
}
